const db = uniCloud.database();
const dbCmd = db.command;
const classifyDB = db.collection('files-classify');
const filesDB=db.collection('admin-files');
import store from '@/store'
import {
	listToTree
} from '../upload.js'
export default {
	data() {
		return {
			tree: [],
			classifyInit: false,
			showPreview:true,
			checkTreeNode:{},
			checkboxValue:[],
		}
	},
	computed: {
		userInfo() {
			return store.state.user.userInfo;
		},
		noClassify() {
			return this.classifyInit && this.tree.length === 0;
		},
		classify(){
			return this.checkTreeNode._id||null;
		}
	},
	watch: {
		userInfo() {
			this._init();
		}
	},
	onReady() {
		this._init();
	},
	methods: {
		async _init() {
			if (this.userInfo && this.userInfo._id) {
				const uid = this.userInfo._id;
				const {
					result
				} = await classifyDB.where({
					uid
				}).get()
				this.classifyInit = true;
				if (!result.code && result.data.length > 0) {
					const data = result.data.map(_ => {
						_.id = _._id;
						_.title = _.name;
						return _
					})
					this.tree = listToTree(result.data, {
						idKey: '_id',
						parentKey: "parent_id"
					});
					this._initFiles()
				}
			}
		},
		
		
		//初始化文件夹
		async initClassify() {
			await classifyDB.add({
				name: '根目录'
			});
			this._init();
		},
		//节点新增按钮点击事件
		addNode(node) {
			const id = node.id,
				that = this;
			uni.showModal({
				title: '新建文件夹',
				editable: true,
				success: function(res) {
					if (res.confirm) {
						const classify = {};
						classify.name = res.content;
						if (id) {
							classify.parent_id = id
						}
						classifyDB.add(classify).then(({
							result
						}) => {
							classify.title = classify.name;
							classify.id = result.id
							that.$refs.tree.create(classify, node);
						});
					} else if (res.cancel) {
						console.log('用户点击取消');
					}
				}
			});
		},
		//节点更新按钮点击事件
		editNode(node) {
			this.$refs.tree.edit(node);
		},
		//修改文件夹名时
		nodeBlur(node) {
			const {
				id,
				title,
				name
			} = node;
			this.$refs.tree.quitEdit(node);
			classifyDB.doc(id).update({
					name: title
				}).then(_ => {
					this.$refs.tree.setAttr(node, 'name', title);
				})
				.catch(_ => {
					this.$refs.tree.setAttr(node, 'title', name);
				});
		},
		//选择文件
		checkFiles(e){
			this.checkboxValue = e.detail.value
		},
		//选择目录
		clickTree(node){
			this.checkTreeNode=node;
			this._initFiles();
		}
	}
}
